/* 用户信息管理页 类组件编程*/
import { Button, Upload, Radio, Input, Space } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React, { Component } from 'react';
import styles from './index.less';
import XLSX from "xlsx";
import {

  FcButton,
  FcCard,
  FcMessage,
  FcModal,
  FcTable,

} from '@ngfed/fc-components';
import columnsData from './data';
import {
  getLogList,
  logDelete,
  upload,
  logDeleteAll
} from './service';


class ExportDatas extends Component {

  state = {
    // 根据条件查询的列表数据
    datas: [],
    // 表头
    columns: [],
    fileList: [],
    uploading: false,
    value: 1,
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
    isModalVisible: false
  };
  // 生命周期 数据初始化方法建议写在这个里面
  componentDidMount() {
    this.getColumns();
    this.getLogDatas();

  }
  //获取默认列表头
  getColumns = () => {
    let columns: any = columnsData;
    columns = [...columns];
    this.setState({
      columns,
    });
  }

  //上传功能，解析并上传
  handleUpload = () => {
    const isCover = this.state.value
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('files[]', file);
    });

    this.setState({
      uploading: true,
    });

    const reader = new FileReader();
    const f = fileList[0];
    reader.onload = function (e) {
      try {

        const datas = e.target.result;
        const workbook = XLSX.read(datas, { type: "binary", }); //解析datas
        const first_worksheet = workbook.Sheets[workbook.SheetNames[0]]; //是工作簿中的工作表的第一个sheet
        console.log(first_worksheet)
        const jsonArr = XLSX.utils.sheet_to_json(first_worksheet, { header: 2, defval: '' }); //将工作簿对象转换为JSON对象数组
        upload(jsonArr, isCover).then(async (res: any) => {

          console.log(res.body)
          if (res.sysHead.retCd == '000000' && res.body!=null) {
            FcMessage.success('Excel上传解析成功！')
          }
          else FcMessage.error('Execl上传失败,请检查格式')
        })

      } catch (e) {
        FcMessage.error('文件类型不正确！或文件解析错误,支持(.xlsx)')
      }



    };
    this.setState({ datas: [] })
    setTimeout(() => {
      this.getLogDatas()

    }, 500);

    reader.readAsBinaryString(f);
    this.setState({
      uploading: false,
    })

  };



  onChange = (e: { target: { value: any; }; }) => {
    console.log('radio checked', e.target.value);
    this.setState({
      value: e.target.value,
    });
  };

  onSelectChange = (selectedRowKeys: any) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
//获取全部日志
  getLogDatas = () => {
    getLogList().then(async (result: any) => {
      this.setState({
        datas: result.body
      });
    });
  };


  isClear = () => {
    this.setState({ loading: true, isModalVisible: true });

  }
  //删除日志-清空
  clearLog = () => {
    logDeleteAll()
    setTimeout(() => {
      this.setState({
        datas:[],
        selectedRowKeys: [],
        loading: false,
        isModalVisible: false
      });

    }, 500);
  }
  //删除日志-选择
  delLog = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    logDelete(this.state.selectedRowKeys)
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
        datas:[],

      });
      this.getLogDatas();

    }, 500);

  }



  render() {

    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;

    const { value } = this.state;

    const { uploading, fileList } = this.state;
    const props = {
      onRemove: (file: any) => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file: any) => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };
    return (
      <div>
        {/* className 规范 */}
        {/* 单个class */}
        {/* <div  className={ styles.boxTitle }></div> */}
        {/* 多个class */}
        {/* <div  className={ `${styles.boxTitle} ${styles.boxText}` }></div> */}
        <div className={styles.box}>

          <>
            <Space direction="vertical">

              <Upload {...props}>
                <Button icon={<UploadOutlined />}>Select File</Button>
              </Upload>

              <Radio.Group onChange={this.onChange} value={value}>
                <Radio value={1}>覆盖</Radio>
                <Radio value={2}>不覆盖</Radio>
              </Radio.Group>

              <Button
                type="primary"
                onClick={this.handleUpload}
                disabled={fileList.length === 0}
                loading={uploading}
                style={{ marginTop: 16 }}
              >
                {uploading ? 'Uploading' : '开始上传'}
              </Button>
            </Space>
          </>
        </div>
        <FcCard>
          <div>
            <div style={{ marginBottom: 16 }}>
              <Space>
                <FcButton type="primary" onClick={this.delLog} disabled={!hasSelected} loading={loading}>
                  删除
                </FcButton>
                <FcButton type="primary" onClick={this.isClear} loading={loading}>
                  清空
                </FcButton>

              </Space>
              <span style={{ marginLeft: 8 }}>
                {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
              </span>
            </div>
            <FcTable rowKey='seqNo' rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.datas} />
          </div>
        </FcCard>
        <FcModal
          cancelText="取消"
          okText="确认"
          title="提示"
          visible={this.state.isModalVisible}
          onOk={this.clearLog}
          onCancel={() => {
            this.setState({ isModalVisible: false });
          }}
        >
          是否确定删除所有日志数据？
        </FcModal>
      </div >
    );
  }
}

export default ExportDatas;



